package com.opticon.vaadinR.ui.panel;

import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.vaadin.Application;
import com.vaadin.addon.tableexport.ExcelExport;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.*;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * This class is a
 */
public class NumericTableTab extends VerticalLayout {
    private static Logger logger = Logger.getLogger(NumericTableTab.class);

    private String COLUMN_LABEL_TYPE = "key";
    private String COLUMN_LABEL_ATTRIBUTE = "attr";
    private String COLUMN_LABEL_VALUE = "value";

    private String iTitle = "SimpleTableTab";
    private Table iTable = null;
    private Button iExcelExportButton = null;

    private final File iFile;
    private final Application iApplication;

    private int[] iNumericColumns = null;
    private int[] iNonNumericColumns = null;

    public NumericTableTab(File aFile, Application aApplication, int[] aNumericColumns) {
        iFile = aFile;
        iApplication = aApplication;
        iNumericColumns = aNumericColumns;
        initialize();
    }


    private void loadData(Table aTable) {
        String lFirstLine = null;
        try {
            List<String> lContent = Files.readLines(iFile, Charset.defaultCharset());
            lFirstLine = lContent.get(0).replaceAll("\"", "");

            String[] lHeader = lFirstLine.split(",");

            indexNumericColumns(lHeader);
            createTableColumns(lHeader, aTable);

            for (int i = 1; i < lContent.size(); i++) {
                String line = lContent.get(i);
                String[] lColumns = line.split(",");

                // Add a new item to the table.
                Object id = aTable.addItem();

                // Add non numeric values
                for (int lColumnNumber : iNonNumericColumns) {
                    String lValue = lColumns[lColumnNumber];
                    aTable.getContainerProperty(id, lHeader[lColumnNumber]).setValue(lValue);
                }

                // Add numeric values
                for (int lColumnNumber : iNumericColumns) {
                    Double lValue = Double.parseDouble(lColumns[lColumnNumber]);
                    aTable.getContainerProperty(id, lHeader[lColumnNumber]).setValue(lValue);
                }
            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    private void indexNumericColumns(String[] aHeader) {
        ArrayList<Integer> lNonNumericColumnList = Lists.newArrayList();
        // Add all indices
        for (int i = 0; i < aHeader.length; i++) {
            lNonNumericColumnList.add(i);
        }
        // Remove numeric indices
        for (int iNumericColumn : this.iNumericColumns) {
            lNonNumericColumnList.remove(iNumericColumn);
        }
        // Convert to int[]
        iNonNumericColumns = new int[lNonNumericColumnList.size()];
        for (int i = 0; i < iNonNumericColumns.length; i++) {
            iNonNumericColumns[i] = lNonNumericColumnList.get(i);
        }
    }

    public Component getComponent() {
        return this;
    }

    public void initialize() {
        this.removeAllComponents();

        setCaption();

        iTable = new Table();
        iTable.setSizeFull();

        loadData(iTable);

        iExcelExportButton = new Button("Export to Excel");
        ThemeResource export = new ThemeResource("../images/table-excel.png");
        iExcelExportButton.setIcon(export);
        iExcelExportButton.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = -73954695086117200L;
            private ExcelExport excelExport;

            public void buttonClick(final Button.ClickEvent event) {
                excelExport = new ExcelExport(iTable);
                excelExport.excludeCollapsedColumns();
                excelExport.setReportTitle("VaadinRExport");
                excelExport.export();
            }
        });

        addComponent(iTable);
        addComponent(iExcelExportButton);


        this.requestRepaintAll();
    }


    /**
     * Create the
     *
     * @param aHeader
     * @param aTable
     */
    private void createTableColumns(String[] aHeader, Table aTable) {
        // Define the Table

        // Add non numeric values
        for (int lColumnNumber : iNonNumericColumns) {
            aTable.addContainerProperty(aHeader[lColumnNumber], Label.class, null);
        }

        // Add numeric values
        for (int lColumnNumber : iNumericColumns) {
            aTable.addContainerProperty(aHeader[lColumnNumber], Double.class, null);
        }
    }

    /**
     * Table formatting
     */
    private void doFormatting() {
        iTable.setWidth("100%");
        iTable.setPageLength(4);
    }


    /**
     * Sets the field's caption <code>String</code>. Caption is the visible
     * name of the field. This method will trigger a
     * {@link com.vaadin.terminal.Paintable.RepaintRequestEvent
     * RepaintRequestEvent}.
     */
    public void setCaption() {
        super.setCaption(iTitle);
    }
}
